<?php
require_once '../sub/init.php';
define('ZEAI2',dirname(__FILE__).DIRECTORY_SEPARATOR);
header("Cache-control: private");
require_once 'chkUadm.php';
if(!ADMQX('lovetest')){exit(noauth('暂无【情感测试】权限'));}
require_once ZEAI.'cache/config_up.php';
require_once ZEAI.'sub/zeai_up_func.php';
if ($submitok == 'ajax_addupdate' || $submitok == 'ajax_modupdate'){
	if(!ifint($kind))json_exit(array('flag'=>0,'msg'=>'请选择所属题库','focus'=>'kind'));
	if (str_len($title) >200 || empty($title) )json_exit(array('flag'=>0,'msg'=>'试题标题填写错误','focus'=>'title'));
	$title = dataIO($title,'in',200);$jsonstr = dataIO($jsonstr,'codein',10000);
	$ifmore = intval($ifmore);
	$content = dataIO($content,'in');
}
switch ($submitok){
	case "ajax_modupdate":
		$title=trimhtml($title);
		if(!ifint($id))json_exit(array('flag'=>0));
		if ($title != $oldtitle ){if ($db->ROW(__TBL_LOVETEST_QUESTION__,"id","title='$title'"))json_exit(array('flag'=>0,'msg'=>'试题标题出现重复，请重试','focus'=>'title'));}
		$db->query("UPDATE ".__TBL_LOVETEST_QUESTION__." SET title='".$title."',ifmore='".$ifmore."',subjsonstr='".$jsonstr."',content='".$content."',kind='$kind' WHERE id=".$id);
		json_exit(array('flag'=>1,'msg'=>'修改成功'));
	break;
	case "ajax_addupdate":
		$title=trimhtml($title);
		if ($db->ROW(__TBL_LOVETEST_QUESTION__,"id","title='$title'"))json_exit(array('flag'=>0,'msg'=>'试题标题出现重复，请重试','focus'=>'title'));
		$db->query("INSERT INTO ".__TBL_LOVETEST_QUESTION__." (title,kind,ifmore,subjsonstr,content) VALUES ('$title','$kind','$ifmore','$jsonstr','$content')");
		json_exit(array('flag'=>1,'msg'=>'添加成功'));
	break;
	case "mod":
		$row = $db->NAME("zeai-udata","id,title,kind,ifmore,subjsonstr,content","id=".$id,__TBL_LOVETEST_QUESTION__);
		if ($row){
			$id = $row['id'];
			$kind = $row['kind'];
			$title = dataIO($row['title'],'out');
			$ifmore = $row['ifmore'];
			$jsonstr = dataIO($row['subjsonstr'],'out');
			$content = dataIO($row['content'],'out');
		}else{exit('forbidden');}
	break;
	case"ajax_del":
		if (!ifint($fid))json_exit(array('flag'=>0,'msg'=>'试题不存在或已被删除'));
		$db->query("DELETE FROM ".__TBL_LOVETEST_QUESTION__." WHERE id=".$fid);
		json_exit(array('flag'=>1,'msg'=>'删除成功'));
	break;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="css/main.css?<?php echo $_ZEAI['cache_str'];?>" rel="stylesheet" type="text/css">
<script src="<?php echo HOST;?>/res/www_zeai_cn.js?<?php echo $_ZEAI['cache_str'];?>"></script>
<style>
#tmp input{margin-right:10px}
#tmp .tr{margin-bottom:10px}
.jsonlist{border-radius:2px;display:inline-block;background-color:#aaa;padding:2px 7px;margin:3px 10px 3px 0;font-size:12px}
.ed{background-color:#FF5722;}
.jsonlistbox{width:700px;overflow:hidden;display:inline-block;float:left;font-size:12px}
.box{min-width:1300px}
</style>
<!-- editor -->
<link rel="stylesheet" href="editor/themes/default/default.css" />
<script charset="utf-8" src="editor/kindeditor.js?1"></script>
<script charset="utf-8" src="editor/lang/zh_CN.js?1"></script>
<script>
var editor;
KindEditor.ready(function(K){
  editor=K.create('textarea[name="content"]',{
	resizeType :1,
	cssData:'body {font-family: "微软雅黑"; font-size: 14px}',
	minWidth : 400,
	allowPreviewEmoticons : true,
	allowImageUpload : true,
	afterBlur:function(){this.sync();},
	items : [
		'undo','redo','fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline','removeformat', '|', 'insertorderedlist','insertunorderedlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull','lineheight','|',
		'selectall','quickformat', '|','image','multiimage','media', '|','plainpaste','wordpaste','hr', 'link', 'unlink','baidumap', '|','clearhtml','source', '|','preview','fullscreen']
  });
});
var up2='<?php echo $_ZEAI['up2'];?>/',upMaxMB=<?php echo $_UP['upMaxMB']; ?>;
</script>
<!--editor end -->
</head>
<body>
<?php 
if($submitok!="add" && $submitok!="mod"){
	if(ifint($kind))$SQL.=" AND kind=".$kind;
	if (!empty($Skey))$SQL = " AND ( title LIKE '%".$Skey."%' ) ";
	$rt = $db->query("SELECT id,title,ifmore,subjsonstr,kind FROM ".__TBL_LOVETEST_QUESTION__." WHERE 1=1 ".$SQL." ORDER BY id DESC");
	$total = $db->num_rows($rt);
	$total_str = '<b>'.$total.'</b>';
}
?>
<div class="box">
	<div class="boxL">
        <a href="lovetest_bank.php">题库设置</a>
        <a href="lovetest_question.php" class="ed">试题设置<?php echo $total_str;?></a>
	</div>
  	<div class="boxR">
        <?php if($submitok == "add" || $submitok == "mod"){?>
        <form action="<?php echo SELF;?>" name="ZEAIFORM" id="ZEAIFORM" method="post">
        <table class="table W95_ Mtop10" style="margin-bottom:100px">
            <tr><td height="50" colspan="2" class="S18 B"><?php if($submitok == 'add')echo '创建';if($submitok == 'mod')echo '修改';?>试题</td></tr>
            <tr>
                <td class="tdL">所属分类</td>
                <td class="tdR">
                <select name="kind" id="kind" class="W500 size2" required>
                <?php
                $rt2=$db->query("SELECT id,title FROM ".__TBL_LOVETEST_BANK__." ORDER BY px DESC,id DESC");
                $total2 = $db->num_rows($rt2);
                if ($total2 <= 0) {
                    alert_adm('请先增加题库','question_store.php');
                } else {?>
                <option value="">选择题库</option>
                <?php
                    for($j=0;$j<$total2;$j++) {
                        $rows2 = $db->fetch_array($rt2,'num');
                        if(!$rows2) break;
                        $clss=($kind==$rows2[0])?' selected':'';
                        echo "<option value=".$rows2[0].$clss.">".dataIO($rows2[1],'out')."</option>";
                    }
                }
                ?>
                </select>    
                </td>
            </tr>
            <tr>
                <td class="tdL">试题标题</td>
                <td class="tdR"><input name="title" type="text" class="W100_ size2" id="title" maxlength="200" value="<?php echo $title;?>"></td>
            </tr>
            <tr>
                <td class="tdL">是否多选</td>
                <td class="tdR">
                <input type="checkbox" id="ifmore" class="switch" value="1"<?php echo ($ifmore == 1)?' checked':'';?>><label for="ifmore" class="switch-label totalflag"><i></i><b>多选</b><b>单选</b></label>
                </td>
            </tr>
            <tr>
                <td class="tdL">选项</td>
                <td class="tdR S12">
                <div id="tmp">
                <?php
                $a = json_decode($jsonstr);
                if (is_array($a) && count($a)>0){
                    for($j=0;$j<count($a);$j++) {
                        $id2    = $a[$j]->i;
                        $value2 = $a[$j]->v;
                        $score2 = $a[$j]->s;
                ?>
                    <div class="tr">标记 <input type="text" class="W80 size1" maxlength="5" placeholder="如:ABCD" value="<?php echo $id2;?>">选项内容 <input type="text" class="W500 size1" maxlength="50" value="<?php echo $value2;?>">分值 <input type="text" class="W50 size1" maxlength="10" placeholder="分值" value="<?php echo $score2;?>"><button type="button" class="btn size1">删除</button></div>
                    <?php }
                }
                ?>
                </div>
                <div><button id="add" type="button" class="btn size1 LAN2 ico">&#xe622; 增加</button></div>
                </td>
            </tr>
            <tr><td class="tdL">详细内容</td><td class="tdR"><img src="images/!.png" width="14" height="14" valign="middle"> <span style="font-size:12px;vertical-align:middle;color:#999">如果从公众号编辑器或外部网页或Word里拷入内容请先过虑垃圾代码，请点击下方</span> <img src="images/cclear.png" class="picmiddle"> <span class="tips picmiddle">图标，然后插入文字内容</span><textarea name="content" id="content" class="textarea_k" style="width:100%;height:300px" ><?php echo $content;?></textarea></td></tr>
          <input name="oldtitle" type="hidden" value="<?php echo $title;?>">
            <input name="submitok" type="hidden" value="ajax_<?php echo $submitok.'update';?>" />
            <?php if ($submitok == 'mod'){?><input name="id" type="hidden" value="<?php echo $id;?>" /><?php }?>
        </table>
        </form>
      <!--MOD END-->
		<?php }else{
			$Skey = trimhtml($Skey);	
		?>
        <!--LIST-->
        <div class="topsearch">
        	<button type="button" class="btn" onClick="zeai.openurl('<?php echo SELF;?>?submitok=add&kind=<?php echo $kind;?>')"><i class="ico">&#xe622;</i> 新增试题</button>　　
            <form name="www_A9A_cn" method="get" action="<?php echo SELF; ?>">
                <input name="Skey" type="text" id="Skey" size="30" maxlength="25" class="input size2" placeholder="按试题标题搜索" value="<?php echo $Skey;?>">
                <input type="hidden" name="kind" value="<?php echo $kind;?>" />
                <button type="submit" class="btn size2"><i class="ico">&#xe6c4;</i> 搜索</button>
            </form>                  
        </div>
	  <?php
        if ($total <= 0 ) {
            if ($submitok !== "add")echo "<div class='nodatatips'>暂无内容　　<a class='btn size2' href=".SELF."?submitok=add&kind=".$kind.">新增试题</a></div>";
        } else {    
            $page_skin = 2;$pagesize=20;require_once ZEAI.'sub/page.php';?>
          <table class="tablelist Mtop20">
            <tr>
                <th width="60" align="center">ID</th>
            	<th width="200" align="left">试题标题</th>
            	<th width="60" align="center">类型</th>
            	<th width="150" align="center">来自题库</th>
              	<th>选项</th>
            	<th width="60" align="left">编辑</th>
              <th width="60" align="left">删除</th>
            </tr>
            <?php
            for($i=1;$i<=$pagesize;$i++) {
                $rows = $db->fetch_array($rt);
                if(!$rows) break;
                $id = $rows['id'];
				$kind = intval($rows['kind']);
                $title = dataIO($rows['title'],'out');
                $ifmore = dataIO($rows['ifmore'],'out');
                $jsonstr= dataIO($rows['subjsonstr'],'out');
				$row = $db->ROW(__TBL_LOVETEST_BANK__,"title","id=".$kind);
				$ftitle= dataIO($row[0],'out');
				if(!empty($Skey))$title = str_replace($Skey,'<font class="Cf00 B">'.$Skey.'</font>',$title);
            ?>
            <tr>
              <td width="60" height="40" align="center"><?php echo $id;?></td>
                <td width="200" align="left" class="padding10"><?php echo $title;?></td>
                <td width="60" align="center"><?php echo ($ifmore == 1)?'多选':'单选';?></td>
                <td width="150" align="center" class="C999"><?php echo $ftitle;?></td>
                <td class="padding10">
                    <?php $a = json_decode($jsonstr,true);?>
                    <div class="jsonlistbox Cfff">
                    <?php
                    for($j=0;$j<@count($a);$j++) {
                        echo '<span class="jsonlist">'.$a[$j]['i'].'：';
                        echo $a[$j]['v']."(".$a[$j]['s']."分)";
                        echo '</span>';
                    }?>
                  </div><a class="FL aHUI" style="display:none">more..</a>
              </td>
                <td width="60" align="left"><a href="<?php echo SELF;?>?submitok=mod&id=<?php echo $id;?>" class="editbtn"></a></td>
           	  <td width="60" align="left"><a clsid="<?php echo $id; ?>" class="delbtn" title='删除'></a></td>
            </tr>
            <?php } ?>
          </table>
      <?php } ?>
      <!--LIST END-->
      	<?php }?>
	</div>
    <div class="clear"></div>
</div>

<?php if ($submitok == "add" || $submitok == "mod") {?>
<div class="savebtnbox"><button type="button" id="save" class="btn size3">确定并保存</button></div>
<?php }else{
	if ($total > $pagesize)?>
    <div class="listbottombox" style="text-align:center"><div class="pagebox"><?php echo $pagelist;?></div></div>
    <?php
}?>
<script>
<?php if ($submitok == "add" || $submitok == "mod") {?>
	zeai.listEach('.tr',function(obj){
		obj.children[3].onclick=function(){this.parentNode.parentNode.removeChild(this.parentNode);}
	});
	add.onclick = function(){
		var text1 = document.createTextNode('标记 '),text2 = document.createTextNode('选项内容 '),text3 = document.createTextNode('分值 ');
		var IDH = zeai.addtag('input');IDH.className = 'W80 size1';IDH.maxLength = 4;IDH.placeholder='如:ABCD';
		var Namee = zeai.addtag('input');Namee.className = 'W500 size1';Namee.maxLength = 50;
		var Score = zeai.addtag('input');Score.className = 'W50 size1';Score.maxLength = 10;
		var Btn = zeai.addtag('button');Btn.className = 'btn size1';Btn.html('删除');Btn.onclick=function(){this.parentNode.parentNode.removeChild(this.parentNode);}
		var tr = zeai.addtag('div');tr.className = 'tr';
		tr.appendChild(text1);tr.appendChild(IDH);tr.appendChild(text2);tr.appendChild(Namee);tr.appendChild(text3);tr.appendChild(Score);tr.appendChild(Btn);tmp.appendChild(tr);
	}
	save.onclick = function(){
		var titleV  = o('title').value;
		var ifmoreV = o('ifmore').checked;
		var kindV = o('kind').value;
		ifmoreV = (ifmoreV==true)?1:0;
		if(!zeai.ifint(kindV)){
			zeai.msg('请选择所属题库',kind);
			return false;
		}
		if(zeai.empty(titleV) || zeai.str_len(titleV)>200){
			zeai.msg('请输入试题标题(1-200字节)',title);
			return false;
		}
		//子选项
		var idARR = [],jsonarr=[];
		zeai.listEach('.tr',function(obj){
			var subid   = obj.children[0];
			var subname = obj.children[1];
			var subscore = obj.children[2];
			if (zeai.empty(subid.value)){zeai.msg('请输入标记',subid);return false;}
			if (zeai.empty(subname.value)){zeai.msg('请输入选项',subname);return false;}
			if (subscore.value!=0){if (!zeai.ifint(subscore.value)){zeai.msg('请输入分值',subscore);return false;}}
			idARR.push(subid.value);
			jsonarr.push({"i":subid.value,"v":subname.value,"s":subscore.value});
		});
		if (idARR.length <= 0){
			zeai.msg('请点一下【增加】小按钮，谢谢');
			return false;
		}
		//子选项结束
		var jsonstr = JSON.stringify(jsonarr);
		var postjson = {"ifmore":ifmoreV,"jsonstr":jsonstr};
		//POST
		zeai.ajax({url:'lovetest_question.php',data:postjson,form:ZEAIFORM},function(e){var rs=zeai.jsoneval(e);zeai.msg(0);
			if (rs.flag == 1){
				zeai.msg(rs.msg,{time:1});
				setTimeout(function(){zeai.openurl('lovetest_question.php');},1000);
			}else if(rs.flag == 0){
				zeai.msg(rs.msg,o(rs.focus));
				return false;
			}		
		});
		return false;
	}
<?php }else{ ?>
	zeai.listEach('.delbtn',function(obj){
		obj.onclick = function(){
			var id = parseInt(obj.getAttribute("clsid"));
			zeai.confirm('★请慎重★　确定真的要删除么？',function(){
				zeai.ajax({url:'lovetest_question.php?submitok=ajax_del&fid='+id},function(e){
					rs=zeai.jsoneval(e);
					zeai.msg(0);zeai.msg(rs.msg);
					if(rs.flag==1){setTimeout(function(){location.reload(true);},1000);}
				});
			});
		}
	});
	zeai.listEach('.jsonlistbox',function(obj){
		var objH = obj.offsetHeight;
		if (objH > 52){
			obj.style.height = '52px';
			var a = obj.nextElementSibling;
			a.show();
			a.onclick = function(){obj.style.height = 'auto';a.hide();}
			obj.onclick = function(){obj.style.height = 'auto';a.hide();}
		}
	});
<?php } ?>
</script>
<?php require_once 'bottomadm.php';?>